'use client';

import * as XLSX from 'xlsx';
import { applyParameterTableUpdates } from './update-parameter-tables';

export interface ExcelData {
  sheetName: string;
  headers: string[];
  rows: (string | number | null)[][];
}

export interface ParsedExcelFile {
  filename: string;
  sheets: ExcelData[];
}

/**
 * [CLIENT-SIDE ONLY]
 * Parses an Excel file from a browser File object.
 * This function uses FileReader and is intended for client-side use.
 * @param file The File object from a file input.
 * @returns A Promise that resolves to a ParsedExcelFile object.
 */
export function parseExcelFile(file: File): Promise<ParsedExcelFile> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target?.result as ArrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        
        const sheets: ExcelData[] = workbook.SheetNames.map(sheetName => {
          const worksheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { 
            header: 1,
            defval: null,
            raw: false
          }) as (string | number | null)[][];
          
          const headers = jsonData[0] as string[] || [];
          const rows = jsonData.slice(1);
          
          const sheetData = {
            sheetName,
            headers: headers.map(h => h?.toString() || ''),
            rows
          };
          
          return applyParameterTableUpdates(sheetData);
        });
        
        resolve({
          filename: file.name,
          sheets
        });
      } catch (error) {
        reject(error);
      }
    };
    
    reader.onerror = () => reject(new Error('Failed to read file'));
    reader.readAsArrayBuffer(file);
  });
} 